package com.zenith.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenith.article.mapper.ArtCategoryMapper;
import com.zenith.article.po.domain.ArtCategory;
import com.zenith.article.po.dto.ArtCategoryDTO;
import com.zenith.article.service.ArtCategoryService;
import com.zenith.common.result.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 文章分类服务实现类
 *
 * @author zenith
 * @since 2025-08-29
 */
@Service
public class ArtCategoryServiceImpl extends ServiceImpl<ArtCategoryMapper, ArtCategory> implements ArtCategoryService {

    @Override
    public PageResult<ArtCategory> getArtCategoryPage(ArtCategoryDTO query) {
        // 构造分页对象
        Page<ArtCategory> page = new Page<>(query.getPageNum(), query.getPageSize());
        
        // 构造查询条件
        LambdaQueryWrapper<ArtCategory> wrapper = new LambdaQueryWrapper<>();
        if (query.getName() != null && !query.getName().isEmpty()) {
            wrapper.like(ArtCategory::getName, query.getName());
        }
        if (query.getStatus() != null) {
            wrapper.eq(ArtCategory::getStatus, query.getStatus());
        }
        
        // 执行分页查询
        page = this.page(page, wrapper);
        
        // 返回分页结果
        return PageResult.ofPage(page.getCurrent(), page.getSize(), page.getTotal(), page.getRecords());
    }

    @Override
    public List<ArtCategory> getArtCategoryTree() {
        // 查询所有分类
        List<ArtCategory> allCategories = this.list();
        
        // 构造树形结构
        return buildCategoryTree(0L, allCategories);
    }

    @Override
    public boolean createArtCategory(ArtCategoryDTO categoryDTO) {
        ArtCategory category = new ArtCategory();
        BeanUtils.copyProperties(categoryDTO, category);
        return this.save(category);
    }

    @Override
    public boolean updateArtCategory(ArtCategoryDTO categoryDTO) {
        ArtCategory category = new ArtCategory();
        BeanUtils.copyProperties(categoryDTO, category);
        return this.updateById(category);
    }

    @Override
    public boolean deleteArtCategory(Long id) {
        return this.removeById(id);
    }

    /**
     * 构造分类树形结构
     *
     * @param parentId 父级ID
     * @param categories 所有分类
     * @return 树形结构
     */
    private List<ArtCategory> buildCategoryTree(Long parentId, List<ArtCategory> categories) {
        return categories.stream()
                .filter(category -> category.getParentId().equals(parentId))
                .peek(category -> category.setChildren(buildCategoryTree(category.getId(), categories)))
                .collect(Collectors.toList());
    }
}